<!--
 * @Author: Wangtao
 * @Date: 2022-05-30 22:55:52
 * @LastEditors: Wangtao
 * @LastEditTime: 2022-06-21 11:21:07
-->
<template>
  <div class="knowledge-box">
    <div class="container" v-show="!preview.isShow">
      <div class="top">
        <div class="search">
          <el-select
            size="mini"
            class="scopeSelect"
            v-model="searchForm.robotId"
            filterable
            :popper-append-to-body="false"
            @change="searchFun"
          >
            <el-option
              v-for="item in robotList"
              :key="item.robotId"
              :label="item.robotName"
              :value="item.robotId"
            >
            </el-option>
          </el-select>
          <el-input
            size="mini"
            class="scopeIpt"
            v-model="searchForm.question"
            placeholder="请输入关键词模糊搜索"
            @clear="searchFun"
            :clearable="true"
            @keyup.enter.native="searchFun"
            @change="searchChange"
          >
            <i
              slot="prefix"
              class="el-input__icon el-icon-search"
              @click="searchFun"
            ></i>
          </el-input>
        </div>
      </div>
      <div class="list">
        <div class="directory" v-if="searchTitle">
          <span v-html="searchTitle"></span>
        </div>
        <div class="content" v-if="konwledgeList.length > 0">
          <div
            :class="[
              'item',
              'clearfix',
              item.correctVisible ? 'force-hover' : ''
            ]"
            v-for="(item, index) in konwledgeList"
            :key="index"
          >
            <span
              class="listFlag V7_iconfont fl V7_iconV7tubiao_xbot-weixuan"
            ></span>
            <div v-html="item.title" class="fl titleItem"></div>
            <div class="fr operation" v-if="!isShowWebchatBtn">
              <el-popover
                placement="bottom"
                width="200"
                trigger="manual"
                :append-to-body="false"
                :popper-options="{ boundariesElement: 'body' }"
                @show="correctPopoverShow(item)"
                v-model="item.correctVisible"
                @hide="correctPopoverHide"
                @after-leave="currentCorrect = ''"
              >
                <el-input
                  type="textarea"
                  :rows="4"
                  resize="none"
                  v-model.trim="currentCorrect"
                >
                </el-input>
                <div class="correct-btn-box">
                  <el-button
                    class="correct-btn"
                    size="mini"
                    @click="correctCancel(item)"
                    >取消</el-button
                  >
                  <el-button
                    class="correct-btn"
                    size="mini"
                    type="primary"
                    @click="agentCorrect(item)"
                    >发送</el-button
                  >
                </div>
                <span slot="reference"
                  ><span
                    style="margin-right: 14px"
                    class="btn"
                    @click="correctBtnClick(item)"
                    >纠错</span
                  ></span
                >
              </el-popover>
              <span
                style="margin-right: 14px"
                class="btn"
                @click="previewFun(item)"
                >预览</span
              >
              <span
                style="margin-right: 14px"
                class="btn"
                @click="copyFun(item.content)"
                >复制</span
              >
            </div>
            <div class="fr operation" v-else>
              <el-popover
                placement="bottom"
                width="200"
                trigger="manual"
                :append-to-body="false"
                :popper-options="{ boundariesElement: 'body' }"
                @show="correctPopoverShow(item)"
                v-model="item.correctVisible"
                @hide="correctPopoverHide"
                @after-leave="currentCorrect = ''"
              >
                <el-input
                  type="textarea"
                  :rows="4"
                  resize="none"
                  v-model.trim="currentCorrect"
                >
                </el-input>
                <div class="correct-btn-box">
                  <el-button
                    class="correct-btn"
                    size="mini"
                    @click="correctCancel(item)"
                    >取消</el-button
                  >
                  <el-button
                    class="correct-btn"
                    size="mini"
                    type="primary"
                    @click="agentCorrect(item)"
                    >发送</el-button
                  >
                </div>
                <span slot="reference"
                  ><span
                    style="margin-right: 14px"
                    class="btn"
                    @click="correctBtnClick(item)"
                    >纠错</span
                  ></span
                >
              </el-popover>
              <span
                style="margin-right: 14px"
                class="btn"
                @click="previewFun(item)"
                >预览</span
              >
              <span
                style="margin-right: 14px"
                class="btn"
                @click="kmUse(item)"
                >使用</span
              >
              <span class="btn" @click="kmSend(item)">发送</span>
            </div>
            <div v-html="item.filterContentText" class="contentItem"></div>
          </div>
          <div class="more" v-if="isShowMore" @click="moreFun">加载更多</div>
        </div>
        <div v-else class="noData">
          <img v-if="!searchForm.robotId" src="@/assets/img/xbot-empty.png" />
          <span>{{ noDataText }}</span>
        </div>
      </div>
    </div>
    <div class="preview" v-show="preview.isShow">
      <div class="previewTop">
        <span class="previewLeft">预览</span>
        <div class="previewRight fr">
          <span v-if="!isShowWebchatBtn">
            <span class="btn" @click="copyFun(preview.content)">复制</span>
          </span>
          <span v-else>
            <span
              style="margin-right: 14px"
              class="btn"
              @click="kmUse(preview)"
              >使用</span
            >
            <span class="btn" @click="kmSend(preview)">发送</span>
          </span>
          <span class="close" @click="previewClose">X</span>
        </div>
      </div>
      <div class="previewContent">
        <div v-html="preview.title" class="contentTitle"></div>
        <div v-html="preview.previewContent"></div>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator'
import { KmModule } from '@/store/modules/km/index'
import { FilterXSS } from 'xss'
import Clipboard from 'clipboard-js'
import { filterContent } from '@/utils/richFilter'
@Component({
  name: 'intelligentAnswer',
  components: {}
})
export default class IntelligentAnswer extends Vue {
  private $message: any
  private $route: any
  private $bus: any
  private $store: any
  private visible = false

  private treeData = []

  private isShowMore = false

  private directory: any = '全部' // 目录标题

  private isShowWebchatBtn: boolean = false // 是否显示在线的按钮

  private preview: any = {
    isShow: false,
    content: '',
    title: '',
    _id: '',
    contentText: '',
    previewContent: '',
    question: '',
    questionId: ''
  }

  private searchForm: any = {
    robotId: '',
    question: '',
    limit: 10,
    page: 1
  }

  private robotList = []

  private konwledgeList: any = []

  private currentId: string = '' // 当前知识点id

  private searchTitle = '' // 是否展示搜索内容

  private currentXbotItem: any = {} // 当前纠错数据
  private currentCorrect = '';

  private allowHumanAssistAccept = false

  private pageData: any = {
    limit: 10,
    page: 1
  }

  get noDataText () {
    if (!this.searchForm.robotId) {
      return '选择机器人后才能使用哦~'
    } else {
      return '暂无数据'
    }
  }

  @Watch('$route')
  private routeChange (to: any) {
    const routeArr = to.path.split('/') // 只有在在线待处理模块下才显示发送和使用按钮
    if (routeArr[3] === 'webchat_todo' && routeArr.length > 4 && routeArr[4] !== 'empty') {
      this.isShowWebchatBtn = true
    } else {
      this.isShowWebchatBtn = false
    }

    // // 当前为在线模块
  }

  private setCurrentRobotByMessageId (messageId, webChatType) {
    const messageList = this.$store.state.webchat.webchatList[webChatType];
    messageList.some((item) => {
      if (item._id === messageId) {
        if (item.robotAssistId) {
          this.searchForm.robotId = item.robotAssistId
        }
        return true;
      }
    })
  }

  public setRobot (id) {
    let idexist = false;
    this.robotList.forEach((item: any) => {
      if (id === item.robotId) {
        idexist = true
      }
    })
    if (idexist) {
      this.searchForm.robotId = id;
    } else {
      this.searchForm.robotId = '';
    }
  }

  public searchFun () { // 搜索知识点
    if (!this.searchForm.robotId) {
      this.$message.error('请选择机器人');
      return;
    }
    if (!this.searchForm.question) {
      this.$message.error('请输入关键词');
      return;
    }
    if (this.searchForm.question) {
      this.searchTitle = `“<span style="color: red">${this.searchForm.question}</span>”相关的搜索结果`;
    } else {
      this.searchTitle = ''
    }
    this.allowHumanAssistAccept = true
    this.getListData()
  }

  private onPopoverShow () {
    this.visible = true
    this.pageData.page = 1
    this.getListData()
  }

  private kmUse (item: any) { // 知识库使用
    console.log(item)
    this.humanAssistAccept(2, item.question, item.questionId)
    const html = filterContent(item.content)
    this.$bus.$emit('kmUse', html)
  }

  private humanAssistAccept (usage, question, questionId) {
    if (!this.allowHumanAssistAccept) {
      // 纠错每搜索一次 只能采纳一次
      return
    }
    this.allowHumanAssistAccept = false
    const actionData = {
      url: '/im-robot/action/xbot/humanAssistAccept',
      method: 'POST',
      data: {
        usage,
        robotId: this.searchForm.robotId,
        question,
        questionId
      }
    }
    KmModule.KmCommonAction(actionData)
  }

  private kmSend (content: any) { // 知识库发送
    this.humanAssistAccept(1, content.question, content.questionId)
    console.log(content)
    this.$bus.$emit('sendInfo', content)
  }

  private previewFun (item: any) { // 知识库预览
    this.preview.isShow = true
    this.preview.content = item.content
    this.preview.title = item.title
    this.preview._id = item._id
    this.preview.contentText = item.contentText
    this.preview.previewContent = item.previewContent
    this.preview.question = item.question
    this.preview.questionId = item.questionId
  }

  private previewClose () { // 预览关闭
    this.preview.isShow = false
    this.preview.content = ''
    this.preview.title = ''
    this.preview._id = ''
    this.preview.contentText = ''
    this.preview.previewContent = ''
    this.preview.question = ''
    this.preview.questionId = ''
  }

  private correctCancel (item) {
    item.correctVisible = false;
  }

  private nodeClick (data: any, node: any) { // 切换目录
    this.directory = ''
    this.searchForm.keywords = '' // 切换目录清空当前搜索项
    this.searchTitle = ''
    this.getAllTitle(node)
    this.directory = this.directory.substr(0, this.directory.length - 1)
    this.pageData.page = 1
    this.currentId = data._id
    this.getListData({ currentId: data._id })
  }

  private getAllTitle (data: any) { // 处理目录
    if (data.level === 1) {
      this.directory = data.label + '/' + this.directory
      return this.directory
    }
    this.directory = data.label + '/' + this.directory
    if (data.parent) {
      this.getAllTitle(data.parent)
    }
  }

  private replaceKeyWord (html, keyWord) {
    if (keyWord) {
      const reg = new RegExp(keyWord, 'g')
      return html.replace(reg, '<strong style="color:red; cursor: pointer">' + keyWord + '</strong>')
    }
    return html
  }

  private getListData (obj?: any) { // 获取知识库列表
    const actionData = {
      url: '/im-robot/action/xbot/searchKnowledge',
      method: 'POST',
      data: {
        ...this.searchForm
      }
    }
    KmModule.KmCommonAction(actionData).then(res => {
      if (res && res.success) {
        const list = res.list || []
        const validArr: any = [];
        list.forEach(item => {
          const returnItem: any = item;
          returnItem.title = this.replaceKeyWord(returnItem.title, this.searchForm.question)
          returnItem.previewContent = this.replaceKeyWord(returnItem.content, this.searchForm.question)
          returnItem.filterContentText = this.replaceKeyWord(returnItem.contentText, this.searchForm.question)
          returnItem.correctVisible = false
          validArr.push(returnItem);
        });
        this.konwledgeList = [...validArr]
        if (list.length < this.searchForm.limit) {
          this.isShowMore = false
        } else {
          this.isShowMore = true
        }
      }
    })
  }

  private copyFun (content: string) { // 复制事件
    if (content) {
      const copyCon = filterContent(content);
      Clipboard.copy(copyCon).then(() => {
        this.$message.success('复制成功')
      }).catch(() => {
        this.$message.error('复制失败')
      })
    }
  }

  private moreFun () { // 点击加载更多
    this.pageData.page++;
    this.searchForm.limit = this.pageData.page * this.pageData.limit;
    this.getListData()
  }

  private getTreeData () { // 获取知识库目录列表
    const actionData = { url: '/im-km/action/catalog/list', method: 'POST', data: { kmType: 'inner' } }
    KmModule.KmCommonAction(actionData).then(res => {
      if (res && res.success) {
        this.treeData = res.data.tree || []
      }
    })
  }

  private getXbotList () {
    const actionData = { url: '/im-robot/action/xbot/list', method: 'POST', data: {} }
    KmModule.KmCommonAction(actionData).then(res => {
      if (res && res.success) {
        this.robotList = res.list || [];
        if (this.robotList.length <= 0) {
          this.$emit('hideRobotTab')
        }
      }
    })
  }

  private agentCorrect () {
    if (!this.currentXbotItem) {
      return
    }
    const query = {
      robotId: this.searchForm.robotId,
      query: this.currentXbotItem.query,
      question: this.currentXbotItem.question,
      questionId: this.currentXbotItem.questionId,
      correct: this.currentCorrect
    }
    const actionData = { url: '/im-robot/action/xbot/agentCorrect', method: 'POST', data: query }
    KmModule.KmCommonAction(actionData).then(res => {
      if (res && res.success) {
        this.currentXbotItem.correctVisible = false
        this.$message.success('发送成功！')
      }
    })
  }

  private correctPopoverShow (item) {
    this.currentXbotItem = item;
  }

  private correctPopoverHide () {
    this.currentXbotItem = {};
  }

  private searchChange (value) {
    this.$emit('searchChange', { value, type: 'knowledgeBase' })
  }

  private correctBtnClick (currentItem) {
    this.konwledgeList.forEach((item) => {
      this.correctCancel(item);
    })
    currentItem.correctVisible = true
  }

  public setQuestion (value) {
    this.searchForm.question = value
  }

  private mounted () {
    const routeArr = this.$route.path.split('/')
    if (routeArr[1] === 'im_workBench' && routeArr.length > 4 && routeArr[4] !== 'empty') {
      this.isShowWebchatBtn = true
    } else {
      this.isShowWebchatBtn = false
    }
    this.getXbotList();
  }
}
</script>
<style lang="stylus" scoped>
@import '~@/common/style/common.styl'
.correct-btn-box
  margin-top 5px
.knowledge-box
  height 500px
.V7_iconV7tubiao_zhishiku
  font-size 18px
  cursor pointer
  color #3d4e66
.kmGlobalPoper
  .btn
    color #008BEE
    cursor pointer
  .preview
    height 500px
    .previewTop
      height 48px
      line-height 48px
      border-bottom 1px solid $border-main
      padding 0px 16px
      .previewLeft
        font-weight 600px
      .close
        color #A6A6AE
        margin-left 10px
        cursor pointer
    .previewContent
      height 440px
      overflow auto
      padding 0px 16px
      .contentTitle
        margin 16px 0px 14px 0px
        font-weight 600
        font-size 14px
        color #303753
  .container
    height 100%
    .top
      border-bottom 1px solid #ECF0F3
      padding 10px
      .V7_iconV7tubiao_zhishiku-zhankai
        color #008BEE
        cursor pointer
      .search
        display inline-block
        margin-left 10px
        width calc(100% - 27px)
        .scopeSelect
          width 80px
          >>>.el-input__inner
            border-right none
            border-radius 4px 0px 0px 4px
        .scopeIpt
          width calc(100% - 80px)
          >>>.el-input__inner
            order-left none
            border-radius 0 4px 4px 0
    .list
      height calc(100% - 70px)
      padding 10px 0px
      .directory
        padding-left 16px
        color #B3B9C7
      .noData
        height 100%
        text-align center
        font-size 14px
        display flex
        flex-direction column
        align-items center
        justify-content center
        span
          color #9499AC
        img
          max-width 100px
      .content
        overflow auto
        height 100%
        .item
          padding 16px
          width 100%
          cursor pointer
          border-bottom 1px solid $border-main
          .listFlag
            font-size 14px
            color #008BEE
            margin-right 5px
          .titleItem
            color #303753
            font-weight 600
            margin-bottom 5px
            width calc(100% - 160px)
            overflow hidden
            text-overflow ellipsis
            white-space nowrap
          .contentItem
            padding-right 10px
            color #71798C
            width 100%
            word-wrap break-word
            display -webkit-box
            -webkit-box-orient vertical
            -webkit-line-clamp 2
            overflow hidden
          .directoryItem
            margin-top 5px
            color #71798c
            width 100%
            overflow hidden
            text-overflow ellipsis
            white-space nowrap
          .operation
            display none
        .item:hover
          background #F3F6F9
        .item:hover .operation
          display block
        .force-hover
          .operation
            display block
          background #F3F6F9
        .more
          text-align center
          color #008BEE
          margin-top 10px
          cursor pointer
</style>
<style lang="stylus">
.el-tabs__content
  overflow initial
.kmGlobalTree
  max-height 400px
  .el-tree
    max-height 352px
    overflow-y auto
  .el-tree-node__label
    font-size 14px
    max-width 90px
    display inline-block
    text-overflow ellipsis
    overflow hidden
    white-space nowrap
  .el-tree-node__content
    margin 5px 0px
  .el-tree__empty-block
    min-height 360px
.kmGlobalPoper
  padding 0px !important
  font-size 12px !important
</style>
